package com.kob.botrunningsystem.service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BotPool extends Thread{
    private final ReentrantLock lock=new ReentrantLock();
    private final Condition condition=lock.newCondition();//条件变量
    private final Queue<Bot> bots=new LinkedList<>();

    public void addBot(Integer userId,String botCode,String input){
        lock.lock();//写队列bots,只要有写操作，就需要jiasuo
        try {
            bots.add(new Bot(userId,botCode,input));
            condition.signalAll();//唤醒
        }finally {
            lock.unlock();
        }
    }

    //消费者
    private void consume(Bot bot){
        Consumer consumer=new Consumer();
        consumer.startTimeout(2000,bot);//bot最多执行2s，之后被截停
    }


    @Override
    public void run() {
        while (true){
            lock.lock();
            if (bots.isEmpty()){//发现生产者空了，阻塞进程
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else {//有任务，消费者开始干活
                Bot bot=bots.remove();//remove返回并删除队头
                lock.unlock();
                consume(bot);//比较耗时,可能执行几秒
            }
        }
    }
}
